import { Injectable } from "@nestjs/common";
import { CreateDraftDto } from "./dto/create-draft.dto";
import { UpdateDraftDto } from "./dto/update-draft.dto";
import { LoggerService } from "@/common/logger/logger.service";
import { PrismaService } from "@/common/prisma/prisma.service";
import { handleError } from "@/utils/handle.error";
import { TUser } from "@/@types/common";
import type { Request } from "express";

@Injectable()
export class DraftService {
  constructor(
    private readonly logger: LoggerService,
    private readonly prismaService: PrismaService,
  ) {
    this.logger.setContext(DraftService.name);
  }

  async create(createDraftDto: CreateDraftDto, req: Request) {
    try {
      this.logger.log(`${this.create.name} was called`);
      const { content, images, tag, date, time, isTemplate, taskName } = createDraftDto;
      const { id: userId } = req.user as TUser;
      const res = await this.prismaService.drafts.create({
        data: {
          taskName,
          content,
          images,
          tag,
          date,
          time,
          isTemplate,
          userId,
        },
        select: {
          id: true,
        },
      });
      return res;
    } catch (error) {
      handleError(this.logger, error, {
        common: "新增失败",
      });
    }
  }

  async query(query: UpdateDraftDto) {
    try {
      this.logger.log(`${this.query.name} was called`);
      const res = await this.prismaService.drafts.findMany({
        where: {
          isDelete: false,
          ...query,
        },
        orderBy: {
          updateTime: 'desc', // 降序排列（最新时间在前）
        },
      });
      return res;
    } catch (error) {
      handleError(this.logger, error, {
        common: "查询列表失败",
      });
    }
  }

  async findAll() {
    try {
      this.logger.log(`${this.findAll.name} was called`);
      const res = await this.prismaService.drafts.findMany({
        where: {
          isDelete: false,
        },
        orderBy: {
          updateTime: 'desc', // 降序排列（最新时间在前）
        },
      });
      return res;
    } catch (error) {
      handleError(this.logger, error, {
        common: "查询列表失败",
      });
    }
  }

  async findAllImage(id: number) {
    try {
      this.logger.log(`${this.findAllImage.name} was called`);
      const res = await this.prismaService.images.findMany({
        where: {
          isDelete: false,
          userId: id,
        }
      });
      return res;
    } catch (error) {
      handleError(this.logger, error, {
        common: "查询列表图片失败",
      });
    }
  }

  async findOne(id: number) {
    try {
      this.logger.log(`${this.findOne.name} was called`);

      const res = await this.prismaService.drafts.findUnique({
        where: {
          id,
        }
      });
      return res;
    } catch (error) {
      handleError(this.logger, error, {
        common: "查询详情失败",
      });
    }
  }


  async update(updateDraftDto: UpdateDraftDto) {
    try {
      this.logger.log(`${this.update.name} was called`);
      const { content, images, date, time, tag, isTemplate, taskName, id } = updateDraftDto;
      const res = await this.prismaService.drafts.update({
        where: {
          id: +id,
        },
        data: {
          taskName,
          content,
          images,
          tag,
          date,
          time,
          isTemplate
        },
        select: {
          id: true,
        },
      });
      return res;
    } catch (error) {
      handleError(this.logger, error, {
        common: "更新失败",
      });
    }
  }

  async remove(id: number) {
    try {
      this.logger.log(`${this.remove.name} was called`);
      const res = await this.prismaService.drafts.update({
        where: {
          id,
        },
        data: {
          isDelete: true,
        },
        select: {
          id: true,
        },
      });
      return res;
    } catch (error) {
      handleError(this.logger, error, {
        common: "更新失败",
      });
    }
  }
}
